import json

import requests
from flask import request, session, current_app

from ...helpers import success_response, error_response
from . import api_bp
from ...get_logger import logger


@api_bp.before_request
def get_ip_port():
    # 获取客户端 IP
    client_ip = request.headers.get('X-Forwarded-For', request.remote_addr)

    # 获取客户端端口
    client_port = request.environ.get('REMOTE_PORT')

    session['client_ip'] = client_ip
    session['client_port'] = client_port


@api_bp.route('/create_batch', methods=['POST'])
def create_batch_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """

    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/create_batch"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/create_batch_ex', methods=['POST'])
def create_batch_ex_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """

    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/create_batch_ex"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/delete_batch', methods=['POST'])
def delete_batch_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """

    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/delete_batch"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/get_last_error', methods=['POST'])
def get_last_error_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/get_last_error"
        response = requests.post(url)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/get_last_full_error_string', methods=['POST'])
def get_last_full_error_string_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/get_last_full_error_string"
        response = requests.post(url)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/set_batch_parameters', methods=['POST'])
def set_batch_parameters_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/set_batch_parameters"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/set_batch_size', methods=['POST'])
def set_batch_size_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/set_batch_size"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/set_batch_start_data', methods=['POST'])
def set_batch_start_data_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/set_batch_start_data"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/set_batch_status', methods=['POST'])
def set_batch_status_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/set_batch_status"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/set_timeout', methods=['POST'])
def set_timeout_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/set_timeout"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/add_parameter', methods=['POST'])
def add_parameter_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/add_parameter"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/get_number_at', methods=['POST'])
def get_number_at_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/get_number_at"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/get_size', methods=['POST'])
def get_size_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/get_size"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))


@api_bp.route('/get_value_at', methods=['POST'])
def get_value_at_func():
    """
    site, area, year, order, batch, recipeCategory, recipe, line, productId, size, useDefaultSize,
                      startMode, plannedStartTimeYear, plannedStartTimeMonth, plannedStartTimeDay, status,
                      parameterList, useDefaultParameterValues, errorMessage,
                      doRepeat
    :return:
    """
    res = request.json
    try:
        logger.info(f'[{session.get("client_ip")}]:[{session.get("client_port")}],params: {json.dumps(res)}')
        json_data = res
        url = f"{current_app.config['BRAUMAT_BASE_URL']}/get_value_at"
        response = requests.post(url, json=json_data)
        if response.status_code != 200:
            return error_response(message=f"{response.text}")
        return success_response(data=response.text)
    except Exception as e:
        return error_response(message=str(e))
